feat: add n_input_nand_gate function to compute NAND for multiple inputs#14625
feat: add n_input_nand_gate function to compute NAND for multiple inputs#14625TTAAAN wants to merge 4 commits intoTheAlgorithms:masterfrom
Conversation
…e error for insufficient elements
| if len(inputs) < 2: | ||
| raise ValueError("Input list must contain at least two elements") | ||
|
|
||
| return int(not all(inputs)) |
There was a problem hiding this comment.
Elegant one-liner — not all(inputs) correctly implements n-input
NAND logic since NAND outputs 0 only when ALL inputs are 1.
Wrapping with int() cleanly converts bool to 0/1.
One edge case worth considering: what if inputs contains values
other than 0 and 1 (e.g. 2 or -1)? all() treats any non-zero
value as True, which could give unexpected results. Consider
adding a validation:
if not all(i in (0, 1) for i in inputs):
raise ValueError("All inputs must be 0 or 1")
| return int(not (input_1 and input_2)) | ||
|
|
||
|
|
||
| def n_input_nand_gate(inputs: list[int]) -> int: |
There was a problem hiding this comment.
Good addition extending the existing nand_gate() to support n
inputs. The function name and type hints are clear and consistent
with the repo's style.
Suggestion: the docstring could mention the relationship to the
existing 2-input nand_gate() for context:
"Generalization of nand_gate() to support n inputs.
Returns 0 only when all inputs are 1, 1 otherwise."
| ValueError: Input list must contain at least two elements | ||
| """ | ||
|
|
||
| if len(inputs) < 2: |
There was a problem hiding this comment.
Good guard for minimum input length. Worth also adding a check
for empty list explicitly since len([]) < 2 is True and would
raise the same error — but the error message "at least two
elements" might confuse users who pass an empty list.
Consider:
if len(inputs) == 0:
raise ValueError("Input list cannot be empty")
if len(inputs) < 2:
raise ValueError("Input list must contain at least two elements")
Describe your change:
Checklist: